package com.ruoyi.web.controller.guomao;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IFileUploadService;
import com.ruoyi.system.service.IGmTenantInfoService;
import com.ruoyi.system.service.ISysFloorService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

/**
 * 国贸租户管理Controller
 *
 * @author xty
 * @date 2021-12-07
 */
@Controller
@RequestMapping("/guomao/tenantManagement")
public class GmTenantManController extends BaseController
{
    private String prefix = "propertys/guomao/tenantManagement";


    @Autowired
    private IGmTenantInfoService tenantInfoService;

//    楼层信息
    @Autowired
    private ISysFloorService floorInfoService;

//    文件传输
    @Autowired
    private IFileUploadService fileUploadService;


//    @RequiresPermissions("property:tenant:view")
    @GetMapping()
    public String tenant(ModelMap modelMap)
    {
        List<SysFloor> floorInfos = floorInfoService.selectSysFloorListAll(new SysFloor());
        modelMap.put("floorInfos",floorInfos);
        return prefix + "/main";
    }

    /**
     * 查询租户管理列表
     */
//    @RequiresPermissions("property:tenant:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(GmTenantInfo tenantInfo)
    {
        startPage();
        List<GmTenantInfo> list = tenantInfoService.selectGmTenantInfoList(tenantInfo);
        for (GmTenantInfo gti:list) {
            int count = fileUploadService.getFileCountByKey(gti.getTenantId());
            gti.setFileCount(count);
        }
        return getDataTable(list);
    }

    /**
     * 新增租户管理
     * 页面跳转
     */
    @GetMapping("/add")
    public String add(ModelMap modelMap)
    {
        List<SysFloor> floorInfos = floorInfoService.selectSysFloorListAll(new SysFloor());
        modelMap.put("floorInfos",floorInfos);
        return prefix + "/add";
    }

    /**
     * 新增保存租户管理
     * 保存新增
     */
//    @RequiresPermissions("property:tenant:add")
    @Log(title = "租户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(GmTenantInfo tenantInfo)
    {
        return toAjax(tenantInfoService.insertGmTenantInfo(tenantInfo));
    }

    /**
     * 修改租户管理
     * 页面跳转
     */
    @GetMapping("/edit/{tenantId}")
    public String edit(@PathVariable("tenantId") String tenantId, ModelMap modelMap)
    {
        GmTenantInfo tenantInfo = tenantInfoService.selectGmTenantInfoById(tenantId);
        modelMap.put("tenantInfo", tenantInfo);
        List<SysFloor> floorInfos = floorInfoService.selectSysFloorListAll(new SysFloor());
        modelMap.put("floorInfos",floorInfos);
        return prefix + "/edit";
    }

    /**
     * 修改保存租户管理
     * 保存修改
     */
//    @RequiresPermissions("property:tenant:edit")
    @Log(title = "租户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(GmTenantInfo tenantInfo)
    {
        return toAjax(tenantInfoService.updateGmTenantInfo(tenantInfo));
    }

    /**
     * 删除租户管理
     */
//    @RequiresPermissions("property:tenant:remove")
    @Log(title = "租户管理", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(tenantInfoService.deleteGmTenantInfoByIds(ids));
    }

    /**
     * 导入租户列表
     * */
    @Log(title = "租户管理", businessType = BusinessType.IMPORT)
//    @RequiresPermissions("property:tenant:import")
    @PostMapping("/importExcel")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<GmTenantInfo> util = new ExcelUtil<>(GmTenantInfo.class);
        List<GmTenantInfo> lists = util.importExcel(file.getInputStream());
        SysUser sysUser = ShiroUtils.getSysUser();
        //校验数据
        String res = tenantInfoService.validateDatas(lists);
        if (StringUtils.isNotBlank(res)){
            return AjaxResult.error(res);
        }
        String message =tenantInfoService.importRelations(lists,updateSupport,sysUser);
        return AjaxResult.success(message);
    }

    /**
     * 导入中的下载模板
     * */
//    @RequiresPermissions("property:tenant:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<GmTenantInfo> util = new ExcelUtil<GmTenantInfo>(GmTenantInfo.class);
        return util.importTemplateExcel("租户信息");
    }



    /**
     * 导出租户管理列表
     */
//    @RequiresPermissions("property:tenant:export")
    @Log(title = "租户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(GmTenantInfo tenantInfo,String ids)
    {
        List<GmTenantInfo> list = new ArrayList<>();
        if(StringUtils.isNotEmpty(ids)){
            String[] tenantIds = Convert.toStrArray(ids);
            for(String tenantId:tenantIds){
                GmTenantInfo thisTenantInfo = tenantInfoService.selectGmTenantInfoById(tenantId);
                list.add(thisTenantInfo);
            }
        }else {
            list = tenantInfoService.selectGmTenantInfoList(tenantInfo);
        }
        ExcelUtil<GmTenantInfo> util = new ExcelUtil<GmTenantInfo>(GmTenantInfo.class);
        return util.exportExcel(list, "tenant");
    }




    /**
     * 跳转上传页面
     */
    @GetMapping("/toUpload/{tenantId}")
    public String toUpload(@PathVariable String tenantId, ModelMap modelMap) {
        List<FileUploadInfo> fileUploadInfoList = fileUploadService.getFileUploadListByKey(tenantId);
        modelMap.put("tenantId",tenantId);
        modelMap.put("fileInfos",fileUploadInfoList);
        return prefix + "/tenantUpload";
    }

    /**
     * 上传文件
     */
    @PostMapping("/Upload")
    @ResponseBody
    public AjaxResult tenantUpload(MultipartFile file)
    {
        String filePath = "";
        try {
            filePath = FileUploadUtils.upload(Global.getGmTenantInfoPath(),file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(file.getOriginalFilename(),filePath);
    }

    /**
     * 保存文件地址到库里
     */
    @PostMapping("/changePath")
    @ResponseBody
    public AjaxResult changePath(String tenantId,String filePath,String fileName) {
        try{
            FileUploadInfo fileUploadInfo = new FileUploadInfo();
            fileUploadInfo.setFileId(UUID.randomUUID().toString().replaceAll("-",""));
            fileUploadInfo.setFileName(fileName);
            fileUploadInfo.setFilePath(filePath);
            fileUploadInfo.setFileType("2");  //基本信息
            fileUploadInfo.setStatus("1");  //有效
            fileUploadInfo.setBelongKey(tenantId);
            fileUploadService.insertFileUpload(fileUploadInfo);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 将文件置为失效
     */
    @PostMapping("/removeAnnex")
    @ResponseBody
    public AjaxResult removeAnnex(String key) {
        //String InfoId,String filePath    目前用不上
        try{
            fileUploadService.deleteFile(key);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("文件删除失败");
        }
        return AjaxResult.success();
    }

    /**
     * 下载文件到指定目录
     */
    @PostMapping("/downloadInfo")
    @ResponseBody
    public AjaxResult downloadInfo(String tenantId) {
        List<FileUploadInfo> fileUploadInfos = fileUploadService.getFileUploadListByKey(tenantId);
        String infoPath = "/profile/gmTenantInfo";
        File dir = new File(Global.getDownloadPath()+tenantId);
        if(!dir.exists()){
            dir.mkdirs();
        }
        if(fileUploadInfos!=null&&fileUploadInfos.size()>0){
            //执行循环将需要下载的文件拷贝到下载目录下
            for(FileUploadInfo fileUploadInfo:fileUploadInfos){
                String newPath = fileUploadInfo.getFilePath().replaceAll(infoPath,Global.getGmTenantInfoPath());
                File file = new File(newPath);
                File newFile = new File(dir + File.separator + fileUploadInfo.getFileName());
                try {
                    Files.copy(file.toPath(),newFile.toPath());
//                    fileUploadInfo.setFilePath(newFile.toPath().toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else{
            return AjaxResult.error("无附件！");
        }
        return AjaxResult.success("success",tenantId);
    }

    /**
     * 将目录中的文件打包下载
     */
    @GetMapping("/downloadInfo")
    public void downloadInfo(String fileName, HttpServletRequest request, HttpServletResponse response) {
        try{
            GmTenantInfo tenantInfo = tenantInfoService.selectGmTenantInfoById(fileName);
            String downloadName = tenantInfo.getTenantName() + "信息附件.zip";

            String sourceFilePath = Global.getDownloadPath() + fileName;
            String zipOutFilePath = Global.getDownloadPath() + downloadName;
            FileUtils.createZip(sourceFilePath,zipOutFilePath);
            try{
                response.setHeader("Content-Type", "application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=" + FileUtils.setFileDownloadHeader(request,downloadName));
                FileUtils.writeBytes(zipOutFilePath,response.getOutputStream());
            }finally {
                try{
                    File zfile = new File(zipOutFilePath);
                    zfile.delete();
                    File sqlFile = new File(sourceFilePath);
                    FileUtils.deleteDir(sqlFile);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
